package org.dandsoft.blackbox.labs.snn;

import java.io.Writer;
import java.io.IOException;

/**
 * User: dvilyuzhanin
 * Date: 26.01.2009 16:17:01
 */
public class SynapsesWriter {

    public final static char FIELDS_SEPARATOR = ';';
    public final static char SYNAPSES_SOURCE_SEPARATOR = ':';
    public final static char SYNAPSES_DESTINATIONS_SEPARATOR = ',';
    public final static char LAYERS_SEPARATOR = '\n';
    public final static char LAYER_START = '!';
    public final static char LAYER_INFO_START = '{';
    public final static char LAYER_INFO_FINISH = '}';

    private boolean isNewLayer;
    private Integer previousSourceNeuron;
    private Writer writer;
    private int layersNumber = -1;

    public SynapsesWriter(Writer writer) {
        this.writer = writer;
        isNewLayer = true;
    }

    public synchronized void writeSynapse(int sourceNeuron, int destinationNeuron) throws IOException {
        if (isNewLayer) {
            layersNumber++;
            writer.write(LAYER_START);
            writer.write(Integer.toHexString(layersNumber));
            isNewLayer = false;
            previousSourceNeuron = null;
        }

        if (previousSourceNeuron == null || previousSourceNeuron != sourceNeuron) {
            writer.write(FIELDS_SEPARATOR);
            writer.write(Integer.toHexString(sourceNeuron));
            writer.write(SYNAPSES_SOURCE_SEPARATOR);
            writer.write(Integer.toHexString(destinationNeuron));
            previousSourceNeuron = sourceNeuron;
        } else {
            writer.write(SYNAPSES_DESTINATIONS_SEPARATOR);
            writer.write(Integer.toHexString(destinationNeuron));
        }
    }

    public synchronized void startNewLayer(int neuronsCount, int synapsesCount) throws IOException {
        if (!isNewLayer) {
            writer.write(FIELDS_SEPARATOR);
            writer.write(LAYER_INFO_START);
            writer.write("nc=" + neuronsCount + ",sc=" + synapsesCount);
            writer.write(LAYER_INFO_FINISH);
            writer.write(LAYERS_SEPARATOR);
        }
        isNewLayer = true;
    }

    public synchronized void flush() throws IOException {
        writer.flush();
    }

    public synchronized void close() throws IOException {
        writer.close();
    }

}


